﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Mvc;
using UserIdentityDemo.Data;
using UserIdentityDemo.Models;
using UserIdentityDemo.Services;
using System.Net;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace UserIdentityDemo.Controllers
{
    public class AccountController : Controller
    {
        private readonly DataContext _dataContext;

        public AccountController(DataContext dataContext)
        {
            _dataContext = dataContext;
        }

        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Register(User user)
        {
            if (ModelState.IsValid)
            {
                _dataContext.Users.Add(user);
                _dataContext.SaveChanges();
                return RedirectToAction("Login");
            }
            return View(user);
        }


        // GET: /<controller>/
        public IActionResult Login(string returnUrl = null)
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(string userName, string password, string returnUrl = null)
        {
            var user = _dataContext.Users.FirstOrDefault(u => u.UserName == userName && u.Password == password);

            if (user == null)
            {
                ViewBag.ErrorMessage = "用户名或密码不正确！";
                return View();
            }
            var ipAddress = HttpContext.Connection.LocalIpAddress;
            var claimsPrincipal = UserAuthorization.GetClaimsPrincipal(user);
            await HttpContext.Authentication.SignInAsync(Constants.MiddlewareScheme, claimsPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });
            return RedirectToLocal(returnUrl);
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.Authentication.SignOutAsync(Constants.MiddlewareScheme);

            return RedirectToAction("Index", "Home");
        }

        private IActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
                return Redirect(returnUrl);
            return RedirectToAction("Index", "Home");
        }


        public IActionResult Forbidden()
        {
            return View();
        }
    }
}